package com.xmqian.app.common.config.network;

import android.support.annotation.NonNull;

import com.xmqian.app.common.utils.logger.LoggerUtil;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.GzipSource;

/**
 * 请求拦截器
 */
public class HttpInterceptorUtils implements Interceptor {

    private static final Charset UTF8 = Charset.forName("UTF-8");
    private LogModel mLogModel = LogModel.SIMPLE;

    public enum LogModel {
        SIMPLE,
        BASIC
    }

    public HttpInterceptorUtils setLogMode(LogModel model) {
        mLogModel = model;
        return this;
    }

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        RequestBody requestBody = request.body();
        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            LoggerUtil.e("网络请求", "请求接口: " + request.url() + "\n"
                    + "请求错误: " + e);
            return null;
        }
        ResponseBody responseBody = response.body();
        long contentLength = responseBody != null ? responseBody.contentLength() : 0;
        Headers resultHeader = response.headers();
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        StringBuilder resultLogger = new StringBuilder("请求接口: " + response.request().url() + "\n"
                + "响应码: " + response.code() + "\n"
                + "响应用时: " + tookMs + "ms" + "\n");
        if (mLogModel != LogModel.SIMPLE) {
            for (int i = 0, count = resultHeader.size(); i < count; i++) {
                resultLogger.append(resultHeader.name(i))
                        .append(": ").append(resultHeader.value(i)).append("\n");
            }
        }
        if (bodyHasUnknownEncoding(request.headers()) && requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (isPlaintext(buffer) && charset != null) {
                resultLogger.append("传递参数: ").append(buffer.readString(charset)).append("\n");
            }
        }

        if (bodyHasUnknownEncoding(response.headers()) && responseBody != null) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            if ("gzip".equalsIgnoreCase(resultHeader.get("Content-Encoding"))) {
                GzipSource gzippedResponseBody = null;
                try {
                    gzippedResponseBody = new GzipSource(buffer.clone());
                    buffer = new Buffer();
                    buffer.writeAll(gzippedResponseBody);
                } finally {
                    if (gzippedResponseBody != null) {
                        gzippedResponseBody.close();
                    }
                }
            }
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (isPlaintext(buffer) && contentLength != 0 && charset != null) {
                resultLogger.append("返回结果: ").append(buffer.clone().readString(charset)).append("\n");
            }
        }
        LoggerUtil.e("网络请求", resultLogger.toString());
        return response;
    }

    private static boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

    private boolean bodyHasUnknownEncoding(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding == null
                || contentEncoding.equalsIgnoreCase("identity")
                || contentEncoding.equalsIgnoreCase("gzip");
    }
}
